<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import {
  getAlertTypeDistribution,
  getAlertTypeStats,
  getAlertTrend,
  getAlertStat
} from '@/api/alert'

const getIcon = (iconName) => ElementPlusIconsVue[iconName]

// Data
const timeRange = ref('month')
const selectedCategory = ref('all')
const pieChartRef = ref(null)
const lineChartRef = ref(null)
let pieChartInstance = null
let lineChartInstance = null

// 修改后的顶部卡片数据
const summaryStats = ref([
  {
    label: '警情总数',
    value: '',
    trend: 18.7,
    icon: 'Bell',
    bgColor: '#4834d4'
  },
  {
    label: '高风险警情占比',
    value: '',
    trend: 5.2,
    icon: 'WarningFilled',
    bgColor: '#ff9f43'
  },
  {
    label: '最常见类型',
    value: '',
    trend: 0, // 无趋势变化，仅显示类型
    icon: 'House',
    bgColor: '#28c76f'
  },
  {
    label: '平均处理时长',
    value: '',
    trend: -10.8,
    icon: 'Clock',
    bgColor: '#00cfe8'
  }
])

const categories = ref([
  { label: '全部类型', value: 'all' },
  { label: '车辆火灾', value: '车辆火灾' },
  { label: '化工火灾', value: '化工火灾' },
  { label: '建筑火灾', value: '建筑火灾' },
  { label: '森林火灾', value: '森林火灾' }
])

const tableData = ref([])

// 饼图数据
const pieData = ref([
  { category: '车辆火灾', count: 0, color: '#4ECDC4' },
  { category: '化工火灾', count: 0, color: '#FF6B6B' },
  { category: '建筑火灾', count: 0, color: '#FFD166' },
  { category: '森林火灾', count: 0, color: '#6A0572' }
])

// 折线图数据
const lineData = ref({
  months: [],
  counts: []
})

const queryTypeStatus = async () => {
  const { data } = await getAlertTypeStats()
  tableData.value = data.map((item) => ({
    ...item,
    avgResponseTime: `${item.avgResponseTime.toFixed(2)}分钟`,
    color: '#' + Math.floor(Math.random() * 16777215).toString(16)
  }))
}

const queryPieData = async () => {
  const { data } = await getAlertTypeDistribution(timeRange.value)
  const distribution = data.distribution
  pieData.value = pieData.value.map((item) => ({
    ...item,
    count: distribution[item.category] || 0
  }))
  initPieChart()
}

const queryLineData = async () => {
  const { data } = await getAlertTrend(selectedCategory.value)
  lineData.value.months = data.months
  if (selectedCategory.value === 'all') {
    lineData.value.counts = data.totalCount
  } else {
    lineData.value.counts = data.alertCountByType[selectedCategory.value] || []
  }
  initLineChart()
}

// 饼图
const initPieChart = () => {
  if (!pieChartRef.value) return
  pieChartInstance = echarts.init(pieChartRef.value)
  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { orient: 'vertical', right: 10, top: 'center' },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false },
        emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
        data: pieData.value.map((item) => ({
          name: item.category,
          value: item.count,
          itemStyle: { color: item.color }
        }))
      }
    ]
  }
  pieChartInstance.setOption(option)
}

// 折线图
const initLineChart = () => {
  if (!lineChartRef.value) return
  lineChartInstance = echarts.init(lineChartRef.value)
  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: lineData.value.months
    },
    yAxis: { type: 'value' },
    series: [
      {
        data: lineData.value.counts,
        type: 'line',
        smooth: true,
        lineStyle: { color: '#4834d4', width: 3 },
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: { color: '#4834d4' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(72, 52, 212, 0.3)' },
            { offset: 1, color: 'rgba(72, 52, 212, 0.1)' }
          ])
        }
      }
    ]
  }
  lineChartInstance.setOption(option)
}

const queryAlertStat = async () => {
  const { data } = await getAlertStat()
  summaryStats.value[0].value = data.totalAlertCount
  summaryStats.value[1].value = data.urgentAlertPercentage
  summaryStats.value[2].value = data.mostCommonAlertType
  summaryStats.value[3].value = data.averageResponseTime
}

onMounted(() => {
  queryPieData()
  queryLineData()
  queryTypeStatus()
  queryAlertStat()
  const resizeHandler = () => {
    pieChartInstance?.resize()
    lineChartInstance?.resize()
  }
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  if (pieChartInstance) {
    pieChartInstance.dispose()
    pieChartInstance = null
  }
  if (lineChartInstance) {
    lineChartInstance.dispose()
    lineChartInstance = null
  }
  window.removeEventListener('resize', () => { })
})

watch([timeRange], () => {
  queryPieData()
})

watch([selectedCategory], () => {
  queryLineData()
})
</script>

<template>
  <div class="alarm-statistics-page">
    <!-- Summary Cards -->
    <section class="statistics-cards">
      <div v-for="(stat, index) in summaryStats" :key="index" class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" :style="{ background: stat.bgColor }">
            <el-icon><component :is="getIcon(stat.icon)" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- Charts Section -->
    <section class="charts-container">
      <!-- Category Distribution -->
      <el-card class="chart-card" shadow="none">
        <template #header>
          <div class="card-header">
            <span class="chart-title">警情类型分布</span>
            <el-radio-group v-model="timeRange" size="small">
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-wrapper" ref="pieChartRef"></div>
      </el-card>

      <!-- Trend Analysis -->
      <el-card class="chart-card" shadow="none">
        <template #header>
          <div class="card-header">
            <span class="chart-title">警情趋势分析</span>
            <el-select
              v-model="selectedCategory"
              size="small"
              placeholder="选择类型"
            >
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </template>
        <div class="chart-wrapper" ref="lineChartRef"></div>
      </el-card>
    </section>

    <!-- Statistics Table -->
    <el-card class="table-card" shadow="none">
      <template #header>
        <div class="card-header">
          <span>本月警情分类统计明细</span>
        </div>
      </template>

      <el-table
        :data="tableData"
        class="modern-table"
        :default-sort="{ prop: 'count', order: 'descending' }"
      >
        <el-table-column prop="alertType" label="警情类型" />
        <el-table-column prop="currentMonthCount" label="警情数量" sortable />
        <el-table-column prop="percentage" label="占比">
          <template #default="{ row }">
            <div class="percentage-cell">
              <span>{{ row.percentage }}%</span>
              <el-progress
                :percentage="row.percentage"
                :color="row.color"
                :show-text="false"
                :stroke-width="8"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="avgResponseTime" label="平均响应时间" sortable />
        <el-table-column prop="monthOverMonthChange" label="变化趋势">
          <template #default="{ row }">
            <el-tag
              :type="row.monthOverMonthChange >= 0 ? 'success' : 'danger'"
              effect="plain"
              round
            >
              {{ row.monthOverMonthChange >= 0 ? '+' : ''
              }}{{ row.monthOverMonthChange }}%
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/scss/abstracts/mixins';

.alarm-statistics-page {
  padding: 2.4rem;
  background: #f5f7fa;
  min-height: 100vh;
}

/* Summary Cards */
.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 2.4rem;
  margin-bottom: 2.4rem;

  .stat-card {
    background: #ffffff;
    border-radius: 1.2rem;
    padding: 2rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-4px);
    }

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 12px;

      .stat-icon {
        width: 4.8rem;
        height: 4.8rem;
        border-radius: 1.2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 24px;
        flex-shrink: 0;
      }

      .stat-info {
        .stat-value {
          font-size: 2.8rem;
          font-weight: 700;
          color: #1f2a44;
          line-height: 1;
        }
        .stat-label {
          font-size: 1.6rem;
          color: #86909c;
          margin-top: 0.5rem;
        }
      }
    }
  }
}

/* Charts Section */
.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 2.4rem;
  margin-bottom: 2.4rem;

  .chart-card {
    border-radius: 1.2rem;
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 0 1rem;

    .card-header {
      @include flexBetween;

      .chart-title {
        font-size: 2rem;
        font-weight: 600;
        color: #1f2a44;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 60%;
      }

      .el-radio-group,
      .el-select {
        flex-shrink: 0;
      }

      .el-radio-group {
        .el-radio-button__inner {
          border-radius: 6px;
        }
      }

      .el-select {
        width: 12rem;
        .el-input__wrapper {
          border-radius: 6px;
          box-shadow: none;
        }
      }

      :deep(.el-radio-button__inner),
      :deep(.el-select__placeholder) {
        font-size: 1.6rem;
      }
    }

    .chart-wrapper {
      height: 40rem;
      width: 100%;
    }
  }
}

/* Statistics Table */
.table-card {
  border-radius: 12px;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 0 1rem;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 2rem;
      font-weight: 600;
      color: #1f2a44;
      white-space: nowrap;
    }
  }

  .modern-table {
    border-radius: 8px;
    overflow: hidden;
    font-size: 1.6rem;
    .el-tag {
      font-size: 1.6rem;
    }

    :deep(.el-table__header th) {
      background: #fafafa;
      color: #1f2a44;
      font-weight: 600;
    }

    :deep(.el-table__row:hover) {
      background: #f9fafc;
    }

    .percentage-cell {
      display: flex;
      align-items: center;
      gap: 1.2rem;

      span {
        min-width: 4rem;
      }

      .el-progress {
        width: 10rem;
      }
    }

    .el-tag {
      border-radius: 6px;
      font-weight: 500;
      padding: 2px 8px;
    }
  }
}

/* Responsive Design */
@media screen and (max-width: 1400px) {
  .alarm-statistics-page {
    .statistics-cards {
      grid-template-columns: repeat(2, 1fr);
    }
    .charts-container {
      grid-template-columns: 1fr;
    }
  }
}

@media screen and (max-width: 768px) {
  .alarm-statistics-page {
    .statistics-cards {
      grid-template-columns: 1fr;
    }
  }
}
</style>
